﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Viettel.VOFFICE.DAO.Models;

namespace Viettel.VOFFICE.DAO.DAL.Repository
{
    public class SystemFunctionRepository : IRepository<v_SystemFunction>
    {
        #region Context
        private VOFFICEContext _context;
        public SystemFunctionRepository(VOFFICEContext context)
        {
            if (context == null)
            {
                throw new Exception("Context must be init");
            }
            this._context = context;
        }
        #endregion

        #region Emplememt Repository
        public IEnumerable<v_SystemFunction> Get()
        {
            return _context.v_SystemFunction.Select(o => o);
        }

        public v_SystemFunction GetById(object id)
        {
            return _context.v_SystemFunction.Find(id);
        }

        public IEnumerable<v_SystemFunction> FindByName(object s)
        {
            return _context.v_SystemFunction.Where(o => o.Name.Equals(s));
        }

        public void Insert(v_SystemFunction T)
        {
            _context.v_SystemFunction.Add(T);
            Save();
        }

        public void Delete(object id)
        {
            var systemFunction = GetById(id);
            if (systemFunction != null)
            {
                Delete(systemFunction);
            }
        }

        public void Delete(v_SystemFunction T)
        {
            _context.v_SystemFunction.Remove(T);
            Save();
        }

        public void Update(v_SystemFunction T)
        {
            _context.Entry(T).State = EntityState.Modified;
            Save();
        }

        public void Save()
        {
            _context.SaveChanges();
        }
        #endregion

        #region Extend Repository
        public IEnumerable<v_SystemFunction> GetByParentId(int parentId)
        {
            try
            {
                var systemFunctionList = _context.v_SystemFunction.Where(s => s.ParentId == parentId);
                return systemFunctionList;
            }
            catch (Exception)
            {
                return null;
            }
            
        } 
        public IEnumerable<v_SystemFunction> GetRootFunction()
        {
            try
            {
                var listRoot = _context.v_SystemFunction.Where(s => s.ParentId == null);
                return listRoot;
            }
            catch (Exception)
            {
                return null;
            }
        } 
        #endregion

    }
}
